package pers.zxk.jlytnews.test;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;

@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    private String filePath; //文件保存路径

    private static final long serialVersionUID = 3465909202303185511L;

    @Override
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        super.init(config);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        super.doGet(req, resp);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 对请求包设置编码
        request.setCharacterEncoding("utf-8");
        // 告知tomcat如何编码,浏览器如何解码
        response.setContentType("text/html; charset=utf-8");

        //获得项目的根目录,并设计文件保存路径
        filePath = getServletContext().getRealPath("/uploads/image");

        // 为了简单，后面也直接就以fileName作为保存文件的名称
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMddHHmmss");
        
        String fileName = dateFormat.format(new Date()) + ".jpg";

        //获取文件类型和大小
        Part part = request.getPart("file");
        System.out.println(part.getContentType());
        System.out.println(part.getSize());

        //获得文本字段,下面方法不可行,只能解析英文和数字，中文即使编码也不行。
        String param = request.getParameter("param");
        System.out.println("只能中文哦：" + param);
        String remarks = request.getParameter("remarks");
        System.out.println("只能中文哦：" + remarks);

        Collection<String> headerNames = part.getHeaderNames();

        // 遍历文件上传域的Header Name
        for (String headerName : headerNames) {
            System.out.println(headerName + "---->" + part.getHeader(headerName));
        }
        // 将文件保存到项目下的uploads文件夹下，为了简单这里没写判断目录是否存在及创建目录的操作，要先确保该目录已经存在
        part.write(filePath + "/" + fileName);
        System.out.println("文件保存在：" + filePath + fileName);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}